package com.miqtech.master.wyrecorder.ui.adapter;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.text.style.StyleSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.miqtech.master.wyrecorder.R;
import com.miqtech.master.wyrecorder.entity.GiftAttachment;
import com.miqtech.master.wyrecorder.utils.DeviceUtils;
import com.miqtech.master.wyrecorder.utils.DownloadImage;
import com.miqtech.master.wyrecorder.utils.L;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomMessage;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomMessageExtension;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomNotificationAttachment;
import com.netease.nimlib.sdk.msg.attachment.MsgAttachment;
import com.netease.nimlib.sdk.msg.constant.MsgTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;

import java.util.List;
import java.util.Random;
import java.util.StringTokenizer;

/**
 * Created by arvin on 2016/11/23.
 */

public class ChatRoomAdapter extends BaseAdapter {
    private final static String TAG = "ChatRoomAdapter";
    private List<Object> mMessageItems;
    private Context mContext;
    private LayoutInflater inflater;

    public ChatRoomAdapter(Context context, List<Object> messageItems) {
        this.mMessageItems = messageItems;
        this.mContext = context;
        inflater = LayoutInflater.from(mContext);
    }

    @Override
    public int getCount() {
        return mMessageItems == null ? 0 : mMessageItems.size();
    }

    @Override
    public Object getItem(int position) {
        return mMessageItems.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.message_item, parent, false);
        }
        TextView tvMessage = (TextView) convertView.findViewById(R.id.tvMessage);
        Object o = mMessageItems.get(position);
        if (o instanceof String) {//字符串
            tvMessage.setText(Html.fromHtml(mContext.getResources().getString(R.string.format_live_notify, o)));
        } else if (o instanceof IMMessage) {//云信消息
            initMessageItem((IMMessage) o, tvMessage);
        }
        return convertView;
    }

    private void initMessageItem(IMMessage message, TextView tv) {
        ChatRoomMessage m = (ChatRoomMessage) message;
        String content = m.getContent();  //消息内容
        MsgAttachment attachment = m.getAttachment();  //消息附加
        String nickName = null;
        ChatRoomMessageExtension ce = m.getChatRoomMessageExtension();
        if (ce != null) {
            nickName = ce.getSenderNick();
        }
        if (TextUtils.isEmpty(nickName)) {
            if (message.getRemoteExtension() != null) {
                try {
                    nickName = message.getRemoteExtension().get("nickname").toString();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        if (attachment != null && TextUtils.isEmpty(nickName) && attachment instanceof ChatRoomNotificationAttachment) {
            ChatRoomNotificationAttachment a = (ChatRoomNotificationAttachment) attachment;
            nickName = a.getOperatorNick();
        }
        if (content == null) {   //content为空 表示 送礼物 进入聊天室
            if (message.getMsgType() == MsgTypeEnum.notification) {
                if (TextUtils.isEmpty(nickName))

				if(message.getFromAccount().isEmpty()){
					nickName = "游客";
				}
				else if(message.getFromAccount().toString().length() > 5) {
					nickName = "游客" + message.getFromAccount().substring(0, 5);
				}else{
					nickName = "游客" + message.getFromAccount().toString();
				}
                tv.setText(Html.fromHtml(mContext.getResources().getString(R.string.format_live_notify_enter_other, nickName)));
            } else {
                if (attachment != null && attachment instanceof GiftAttachment) {
                    initGiftMsg(message, tv);
                }
            }

        } else {  //content 不为空 表示发消息，机器人进入（伪  实际也是发消息）
            if (content.contains("欢迎") && content.contains("进入直播间") &&  TextUtils.isEmpty(nickName) ) {
                content = content.replace("欢迎", "");
                content = content.replace("进入直播间", "");
                tv.setText(Html.fromHtml(mContext.getResources().getString(R.string.format_live_notify_enter_other, content)));
            } else {
                tv.setText(Html.fromHtml(mContext.getResources().getString(R.string.format_live_message, "" + nickName, "" + content)));
            }
        }
    }

    private void initGiftMsg(IMMessage message, TextView tv) {
        GiftAttachment attcachment = (GiftAttachment) message.getAttachment();
        String strGiftMessage;
        String senderName = attcachment.getSenderName() + " :  ";
        String giftName = "送给主播1个" + attcachment.getGiftName();
        String giftNumStr = "";
        String giftUrl = attcachment.getGiftShowImage();
        if (!TextUtils.isEmpty(attcachment.getGiftNum())) {
            int giftNum = Integer.parseInt(attcachment.getGiftNum());
            if (giftNum > 1) {
                giftNumStr = "  " + attcachment.getGiftNum() + "连击！";
                //                 giftHolder.tvGiftNum.setText(attcachment.getGiftNum() + "连击！");
            }
        }
        strGiftMessage = senderName + giftName + "G" + giftNumStr;
        SpannableStringBuilder builder = new SpannableStringBuilder(strGiftMessage);
        ForegroundColorSpan messageColor = new ForegroundColorSpan(mContext.getResources().getColor(R.color.gift_yellow));
        ForegroundColorSpan giftNumColor = new ForegroundColorSpan(mContext.getResources().getColor(R.color.orange));
        builder.setSpan(messageColor, 0, (senderName + giftName).length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        builder.setSpan(giftNumColor, (senderName + giftName).length(), strGiftMessage.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        Drawable gift = new BitmapDrawable(mContext.getResources(), DownloadImage.getInstance().getBitmap(giftUrl));
        int size = DeviceUtils.dp2px(mContext, 10);
        gift.setBounds(0, 0, size, size);
        ImageSpan imageSpan = new ImageSpan(gift, ImageSpan.ALIGN_BASELINE);
        builder.setSpan(imageSpan, (senderName + giftName).length(), (senderName + giftName).length() + 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

        builder.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), (senderName + giftName).length() + 1, strGiftMessage.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv.setText(builder);
    }


}
